package com.example.hfweather.adapter

import android.util.SparseArray
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.example.hfweather.ui.home.HomeFragment
import com.example.hfweather.ui.me.MeFragment
import com.example.hfweather.ui.start.StarListFragment


class ViewPagerAdapter(fragmentActivity: FragmentActivity): FragmentStateAdapter(fragmentActivity) {
    //        定义缓存数组
    private val fragmentsCache = SparseArray<Fragment>()
    override fun createFragment(position: Int): Fragment {
//        1. 判断缓存数组中是否有Fragment
        var cachedFragment = fragmentsCache[position]
//       判断并返回
        return if (cachedFragment != null) {
            cachedFragment
        } else {
//           创建Fragment
        val  newFragment =  when (position) {
                0 -> HomeFragment()
                1 -> StarListFragment()
                2 -> MeFragment()
                else ->throw IllegalArgumentException("Invalid position: $position")
            }
//            把Fragment缓存起来
            fragmentsCache.put(position, newFragment)
//            返回结果
            newFragment

        }

    }

    /**
     * 返回Fragment（页面）数量
     */
    override fun getItemCount(): Int {
        return 3
    }
}